package com.jshoperxms.controller.mall.backstage.coupon;

import com.jshoperxms.Response;
import com.jshoperxms.components.upload.qiniu.ImgFileBean;
import com.jshoperxms.controller.mall.backstage.base.BaseTController;
import com.jshoperxms.controller.mall.backstage.base.IBaseCtrl;
import com.jshoperxms.controller.mall.backstage.base.SearchModel;
import com.jshoperxms.controller.mall.backstage.vo.coupon.CouponTVo;
import com.jshoperxms.controller.utils.BaseTools;
import com.jshoperxms.controller.utils.DateTools;
import com.jshoperxms.controller.utils.enums.BaseEnums;
import com.jshoperxms.controller.utils.enums.CouponEnums;
import com.jshoperxms.controller.utils.enums.GoodsCommentEnums;
import com.jshoperxms.controller.utils.statickey.SerialKeys;
import com.jshoperxms.controller.utils.statickey.StaticKey;
import com.jshoperxms.controller.utils.statickey.TagWords;
import com.jshoperxms.controller.utils.statickey.WarnWrods;
import com.jshoperxms.entity.CouponT;
import com.jshoperxms.entity.GoodsTypeT;
import com.jshoperxms.entity.ProductT;
import com.jshoperxms.entity.StoreInfoT;
import com.jshoperxms.service.CouponTService;
import com.jshoperxms.service.GoodsTypeTService;
import com.jshoperxms.service.ProductTService;
import com.jshoperxms.service.StoreInfoTService;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by sdywcd on 17/1/10.
 * Des:优惠券基础信息
 */
@Controller
@RequestMapping("/mall/coupon")
public class CouponTController extends BaseTController implements IBaseCtrl<CouponTVo> {

    @Resource
    private CouponTService couponTService;

    @Resource
    private StoreInfoTService storeInfoTService;

    @Resource
    private GoodsTypeTService goodsTypeTService;

    @Resource
    private ProductTService productTService;
    private Map<String,Object> responsedata=new HashMap<>();

    @RequestMapping(value="/save",method= RequestMethod.POST)
    @Override
    public ResponseEntity save(@RequestBody CouponTVo rq) throws ParseException {
        CouponT bean=new CouponT();
        bean.setId(this.serial.Serialid(SerialKeys.COUPONT));
        Map<String,String>map= BaseTools.parseImg(rq.getMainimg());
        bean.setMainimg(map.get(TagWords.NORMALFILEPATH));
        bean.setSmainimg(map.get(TagWords.COMPRESSFILEPATH));
        String begintime= StaticKey.EMPTY;
        String endtime= StaticKey.EMPTY;
        if(StringUtils.isNotBlank(rq.getReservationtime())){
            String times[]=StringUtils.split(rq.getReservationtime(), TagWords.HR);
            begintime=times[0];
            endtime=times[1];
        }
        bean.setEndtime(BigInteger.valueOf(DateTools.formatStringDate2Long(endtime)));
        bean.setBegintime(BigInteger.valueOf(DateTools.formatStringDate2Long(begintime)));
        bean.setCoupontitle(rq.getCoupontitle());
        bean.setUserangenote(rq.getUserangenote());
        bean.setRangetype(rq.getRangetype());
        bean.setLimituseprice(rq.getLimituseprice());
        bean.setTotal(0);
        bean.setBindtotal(0);
        bean.setCoupontype(CouponEnums.TYPE.MONEY.getState());
        bean.setMoney(rq.getMoney());
        if(StringUtils.equals(CouponEnums.RangeType.ALLPlANTFORM.getState(),rq.getRangetype())){
            bean.setRangecontentid(StaticKey.ZERO);
        }else{
            bean.setRangecontentid(rq.getRangecontentid());
        }
        bean.setStatus(rq.getStatus());
        bean.setCreatetime(DateTools.getSystemTimeBi());
        bean.setUpdatetime(DateTools.getSystemTimeBi());
        bean.setSort(1);
        bean.setVersiont(1);
        bean.setCreatorid(BaseTools.getAdminCreateId());
        bean.setReviewed(GoodsCommentEnums.CommentReviewed.NO.getState());
        this.couponTService.save(bean);
        responsedata.put(TagWords.SUCCESS, true);
        responsedata.put(TagWords.MSG,TagWords.OPERATION_SUCCESS);
        return Response.success(responsedata);
    }

    @RequestMapping(value="/find",method= RequestMethod.POST)
    @Override
    public ResponseEntity find(@RequestBody CouponTVo rq) {
        if(StringUtils.isBlank(rq.getId())){
            responsedata.put(TagWords.SUCCESS,false);
            responsedata.put(TagWords.MSG, WarnWrods.ERROR_PARAMS);
        }else{
            CouponT bean=this.couponTService.findByPK(CouponT.class,rq.getId());
            if(bean!=null){
                ImgFileBean ifb=new ImgFileBean();
                ifb.setNormalfilepath(bean.getMainimg());
                ifb.setCompressfilepath(bean.getSmainimg());
                ifb.setBasepath(StaticKey.EMPTY);
                String time=DateTools.formateLongDateToString(bean.getBegintime().longValue())+TagWords.HR+DateTools.formateLongDateToString(bean.getEndtime().longValue());
                //店铺优惠券
                if(StringUtils.equals(bean.getRangetype(),CouponEnums.RangeType.STORE.getState())){
                    Criterion criterion=Restrictions.eq("id",bean.getRangecontentid());
                    StoreInfoT storeInfoT=this.storeInfoTService.findOneByCriteria(StoreInfoT.class,criterion);
                    if(storeInfoT!=null){
                        responsedata.put("store",storeInfoT);
                    }
                }
                //品类优惠券
                if(StringUtils.equals(bean.getRangetype(),CouponEnums.RangeType.GOODSTYPE.getState())){
                    Criterion criterion=Restrictions.eq("goodstypeid",bean.getRangecontentid());
                    GoodsTypeT goodsTypeT=this.goodsTypeTService.findOneByCriteria(GoodsTypeT.class,criterion);
                    if(goodsTypeT!=null){
                        responsedata.put("goodstype",goodsTypeT);
                    }
                }
                //货物优惠券
                if(StringUtils.equals(bean.getRangetype(),CouponEnums.RangeType.PRODUCT.getState())){
                    Criterion criterion=Restrictions.eq("productid",bean.getRangecontentid());
                    ProductT productT=this.productTService.findOneByCriteria(ProductT.class,criterion);
                    if(productT!=null){
                        responsedata.put("product",productT);
                    }
                }

                responsedata.put("reservationtime",time);
                responsedata.put(TagWords.IFB,ifb);
                responsedata.put(TagWords.BEAN,bean);
                responsedata.put(TagWords.SUCCESS,true);
                responsedata.put(TagWords.MSG,TagWords.OPERATION_SUCCESS);
            }

        }
        return Response.success(responsedata);
    }

    @RequestMapping(value="/del",method= RequestMethod.POST)
    @Override
    public ResponseEntity del(@RequestBody CouponTVo rq) {
        if(StringUtils.isBlank(rq.getId())){
            responsedata.put(TagWords.SUCCESS,false);
            responsedata.put(TagWords.MSG,WarnWrods.ERROR_PARAMS);
        }else{
            this.couponTService.delCouponTransactional(rq);
            responsedata.put(TagWords.SUCCESS,true);
            responsedata.put(TagWords.MSG,TagWords.OPERATION_SUCCESS);
        }
        return Response.success(responsedata);
    }


    @RequestMapping(value="/update",method= RequestMethod.POST)
    @Override
    public ResponseEntity update(@RequestBody CouponTVo rq) throws ParseException {
        if(StringUtils.isBlank(rq.getId())){
            responsedata.put(TagWords.SUCCESS,false);
            responsedata.put(TagWords.MSG,WarnWrods.ERROR_PARAMS);
        }else{
            CouponT bean=this.couponTService.findByPK(CouponT.class,rq.getId());
            if(bean!=null){
                Map<String,String>map= BaseTools.parseImg(rq.getMainimg());
                bean.setMainimg(map.get(TagWords.NORMALFILEPATH));
                bean.setSmainimg(map.get(TagWords.COMPRESSFILEPATH));
                String begintime= StaticKey.EMPTY;
                String endtime= StaticKey.EMPTY;
                if(StringUtils.isNotBlank(rq.getReservationtime())){
                    String times[]=StringUtils.split(rq.getReservationtime(), TagWords.HR);
                    begintime=times[0];
                    endtime=times[1];
                }
                bean.setEndtime(BigInteger.valueOf(DateTools.formatStringDate2Long(endtime)));
                bean.setBegintime(BigInteger.valueOf(DateTools.formatStringDate2Long(begintime)));
                bean.setCoupontitle(rq.getCoupontitle());
                bean.setUserangenote(rq.getUserangenote());
                bean.setRangetype(rq.getRangetype());
                bean.setLimituseprice(rq.getLimituseprice());
                bean.setCoupontype(CouponEnums.TYPE.MONEY.getState());
                bean.setMoney(rq.getMoney());
                if(StringUtils.equals(CouponEnums.RangeType.ALLPlANTFORM.getState(),rq.getRangetype())){
                    bean.setRangecontentid(StaticKey.ZERO);
                }else{
                    bean.setRangecontentid(rq.getRangecontentid());
                }
                bean.setStatus(rq.getStatus());
                bean.setUpdatetime(DateTools.getSystemTimeBi());
                bean.setVersiont(bean.getVersiont()+1);
                this.couponTService.update(bean);
                responsedata.put(TagWords.SUCCESS,true);
                responsedata.put(TagWords.MSG,TagWords.OPERATION_SUCCESS);
            }
        }
        return Response.success(responsedata);
    }

    @Override
    public ResponseEntity findAll() {
        return null;
    }

    @RequestMapping(value="/findByPage",method= RequestMethod.POST)
    @Override
    public ResponseEntity findByPage(SearchModel searchModel, @RequestParam("search[value]") String search, @RequestParam("order[0][column]") String ordervalue, @RequestParam("order[0][dir]") String ordertype) {
        findCustomSearch(searchModel,search,ordervalue,ordertype);
        return Response.success(responsedata);
    }

    @Override
    public void findCustomSearch(SearchModel searchModel, String search, String ordervalue, String ordertype) {
        if(searchModel.getIsCustomSearch()==1){
            int currentPage=searchModel.getCalCurrentPage();
            int lineSize = searchModel.getLength();
            Criterion criterion= Restrictions.ne(TagWords.STATUS, BaseEnums.DataUsingState.DEL.getState());
            if(StringUtils.isNotBlank(searchModel.getCouponrangetype())){
                criterion=Restrictions.and(criterion).add(Restrictions.eq("rangetype",searchModel.getCouponrangetype()));
            }
            if(StringUtils.isNotBlank(searchModel.getName())){
                criterion=Restrictions.and(criterion).add(Restrictions.like("coupontitle",searchModel.getName(), MatchMode.ANYWHERE));
            }
            if(StringUtils.isNotBlank(search)){
                criterion=Restrictions.and(criterion).add(Restrictions.like("coupontitle",search,MatchMode.ANYWHERE));
            }
            int records=this.couponTService.count(CouponT.class,criterion).intValue();
            searchModel.setRecordsTotal(records);
            searchModel.setRecordsFiltered(records);
            responsedata.put(TagWords.RECORDSTOTAL,records);
            responsedata.put(TagWords.RECORDSFILTERED,records);
            List<CouponT> list = this.couponTService.findByCriteriaByPage(
                    CouponT.class, criterion, Order.desc(TagWords.UPDATETIME), currentPage,
                    lineSize);
            this.processPageListT(list);
        }else{
            if(StringUtils.isNotBlank(search)){
                filterSearch(searchModel,search);
            }else{
                findDefaultAll(searchModel,ordervalue,ordertype);
            }
        }
    }


    @Override
    public void filterSearch(SearchModel searchModel, String search) {
        int currentPage=searchModel.getCalCurrentPage();
        int lineSize = searchModel.getLength();
        Criterion criterion=Restrictions.ne(TagWords.STATUS, BaseEnums.DataUsingState.DEL.getState());
        if(StringUtils.isNotBlank(searchModel.getCouponrangetype())){
            criterion=Restrictions.and(criterion).add(Restrictions.eq("rangetype",searchModel.getCouponrangetype()));
        }
        criterion=Restrictions.and(criterion).add(Restrictions.like("coupontitle",search,MatchMode.ANYWHERE));
        int records=this.couponTService.count(CouponT.class,criterion).intValue();
        searchModel.setRecordsTotal(records);
        searchModel.setRecordsFiltered(records);
        responsedata.put(TagWords.RECORDSTOTAL,records);
        responsedata.put(TagWords.RECORDSFILTERED,records);
        List<CouponT> list = this.couponTService.findByCriteriaByPage(
                CouponT.class, criterion,Order.desc(TagWords.UPDATETIME), currentPage,
                lineSize);
        this.processPageListT(list);
    }

    @Override
    public void findDefaultAll(SearchModel searchModel, String ordervalue, String ordertype) {
        int currentPage=searchModel.getCalCurrentPage();
        int lineSize = searchModel.getLength();
        Criterion criterion=Restrictions.ne(TagWords.STATUS, BaseEnums.DataUsingState.DEL.getState());
        if(StringUtils.isNotBlank(searchModel.getCouponrangetype())){
            criterion=Restrictions.and(criterion).add(Restrictions.eq("rangetype",searchModel.getCouponrangetype()));
        }
        int records=this.couponTService.count(CouponT.class,criterion).intValue();
        searchModel.setRecordsFiltered(records);
        searchModel.setRecordsTotal(records);
        responsedata.put(TagWords.RECORDSTOTAL,records);
        responsedata.put(TagWords.RECORDSFILTERED,records);
        Order order=BaseTools.orderByParam(TagWords.UPDATETIME,ordervalue,ordertype);
        List<CouponT> list = this.couponTService.findByCriteriaByPage(
                CouponT.class, criterion,order, currentPage,
                lineSize);
        this.processPageListT(list);
    }

    private void processPageListT(List<CouponT> list) {
        List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
        for (CouponT bean:list) {
            if(StringUtils.isBlank(bean.getSmainimg())){
                bean.setSmainimg(bean.getMainimg());
            }
            Map<String, Object> cellMap = new HashMap<String, Object>();
            cellMap.put("id", bean.getId());
            cellMap.put("smainimg",bean.getSmainimg());
            cellMap.put("coupontitle", bean.getCoupontitle());
            cellMap.put("time",DateTools.formateLongDateToString(bean.getBegintime().longValue())+TagWords.HR+DateTools.formateLongDateToString(bean.getEndtime().longValue()));
            cellMap.put("rangetype",CouponEnums.RangeType.getName(bean.getRangetype()));
            cellMap.put("limituseprice",bean.getLimituseprice());
            cellMap.put("money", bean.getMoney());
            cellMap.put("total", bean.getTotal());
            cellMap.put("bindtotal",bean.getBindtotal());
            cellMap.put("status", BaseEnums.DataUsingState.getName(bean.getStatus()));
            cellMap.put("updatetime", DateTools.formateLongDateToString(bean.getUpdatetime().longValue()));
            cellMap.put("version", bean.getVersiont());
            data.add(cellMap);
        }
        responsedata.put(TagWords.DATA, data);
    }


    @Override
    public void processPageList(List<CouponTVo> list) {

    }

    @Override
    public boolean checkDuplicates(String str) {
        return false;
    }
}
